<?php
/**
 * Created by PhpStorm.
 * User: chang
 * Date: 2019/4/1
 * Time: 11:54
 */

namespace App\Http\Model;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Task extends Base
{
    protected $taskConfigTable = 'task_config';
    protected $taskServiceTable = 'task_service';
    protected $taskRewardRuleTable = 'task_reward_rule';
    protected $userTaskCompleteTable = 'task_user_complete';
    protected $userTaskLogTable = 'task_user_log';
    protected $userTaskRewardLogTable = 'task_user_reward_log';
    const SHOW_COMPLETE_LIST = [1, 2];

    const CONFIG_BAG_PIECE = array(20=>5,21=>15,22=>25);

    protected $redisTaskUserExperience = 'TASK:USER:EXPERIENCE:';//总经验值
    protected $redisTaskUserAvlExperience = 'TASK:USER:AVL:EXPERIENCE:'; //可用经验值
    protected $redisTableUserReceive = 'TASK:USER:RECEIVE:'; //领取状态

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }


    /*
     * task_config Model
     * */

    /**
     * 根据ID获取获取
     * @param $id
     * @return array
     * */
    public function getDataById($id)
    {
        $row = DB::table($this->taskConfigTable)
            ->where(['id' => $id, 'is_delete' => 0])
            ->first();
        return self::objToArray($row);
    }

    /**
     * 获取任务列表
     * @param int $taskType
     * @return array
     * */
    public function getTaskList($taskType = 1)
    {
        $condition[] = ["is_delete", "=", 0];
        $condition[] = ["is_open", "=", 1];
        $condition[] = ["task_type", "=", $taskType];

        $where = DB::table($this->taskConfigTable)
            ->where($condition);

        $ret =$where
            ->orderBy("id", "asc")
            ->get(["id", "name", "type", "action", "cycle", "msg", "content", "task_type"]);
        $data = self::objToArray($ret);
        return $data;
    }



    /*
     * task_service Model
     * */

    /**
     * 根据任务Id获取任务条件列表
     * @param  $taskIds
     * @return array
     * */
    public function getTaskServiceListByTaskIds($taskIds)
    {
        $condition[] = ["is_delete", "=", 0];
        $condition[] = ["is_open", "=", 1];

        $where = DB::table($this->taskServiceTable)
            ->where($condition)
            ->whereIn("config_id", $taskIds);

        $ret =$where
            ->orderBy("id", "asc")
            ->get();
        $data = self::objToArray($ret);
        return $data;
    }



    /*
     * user_task_complete Model
     * */

    /**
     * 根据任务Id 完成任务条件ID 获取用户领取任务列表
     * @param $userId
     * @param $taskServiceId
     * @param $start_time
     * @param $stop_time
     * @return array
     * */
    public function getUserTaskCompleteByUserIdAndServiceIdAndTime($userId, $taskServiceId, $start_time, $stop_time)
    {
        $condition[] = ["is_delete", "=", 0];

        $where = DB::table($this->userTaskCompleteTable)
            ->where($condition)
            ->where("user_id", $userId)
            ->where("service_id", $taskServiceId);

        # 根据时间筛选
        if ($start_time != 0 && $stop_time != 0) {
            $where = $where->where("created_at", ">=", $start_time);
            $where = $where->where("created_at", "<=", $stop_time);
        }
        $ret =$where
            ->orderBy("id", "asc")
            ->first();
        $data = self::objToArray($ret);
        return $data;
    }


    /*
     * user_task_reward_log Model
     * */

    /**
     * 根据任务Id 完成任务条件ID 获取用户领取任务列表
     * @param $userId
     * @param $taskConfigId
     * @param $start_time
     * @param $stop_time
     * @return array
     * */
    public function getUserTaskRewardByUserIdAndConfigIdAndTime($userId, $taskConfigId, $start_time, $stop_time)
    {
        $condition[] = ["is_delete", "=", 0];

        $where = DB::table($this->userTaskRewardLogTable)
            ->where($condition)
            ->where("user_id", $userId)
            ->where("config_id", $taskConfigId);

        # 根据时间筛选
        if ($start_time != 0 && $stop_time != 0) {
            $where = $where->where("created_at", ">=", $start_time);
            $where = $where->where("created_at", "<=", $stop_time);
        }
        $ret =$where
            ->orderBy("id", "asc")
            ->first();
        $data = self::objToArray($ret);
        return $data;
    }

    /**
     * 设置账号是否异常
     * @param $id
     * @param $status 0 - 未发放。1 已发放
     * @return boolean
     */
    public function setUserTaskRewardStatus($id, $status){
        if ($status == 1) {
            $data['reward_status'] = $status;
            $data['reward_at'] = time();
            $ret = DB::table($this->userTaskRewardLogTable)
                ->where("id", "=", $id)
                ->update($data);
            return $ret;
        }
    }


    /*
     * user_task_log Model
     * */
    /**
     * 根据任务Id 完成任务条件ID 获取用户领取任务列表
     * @param $userId
     * @param $taskServiceId
     * @param $start_time
     * @param $stop_time
     * @return array
     * */
    public function getUserTaskLogByUserIdAndServiceIdAndTime($userId, $taskServiceId, $start_time, $stop_time)
    {
        $condition[] = ["is_delete", "=", 0];

        $where = DB::table($this->userTaskLogTable)
            ->where($condition)
            ->where("user_id", $userId)
            ->where("service_id", $taskServiceId);

        # 根据时间筛选
        if ($start_time != 0 && $stop_time != 0) {
            $where = $where->where("created_at", ">=", $start_time);
            $where = $where->where("created_at", "<=", $stop_time);
        }
        $ret =$where
            ->orderBy("id", "asc")
            ->get();
        $data = self::objToArray($ret);
        return $data;
    }


    /*
     * task_reward_rule Model
     * */
    /**
     * 根据任务Id获取任务奖励列表
     * @param  $taskIds
     * @return array
     * */
    public function getTaskRewardRuleList($taskIds)
    {
        $where = DB::table($this->taskRewardRuleTable)
            ->whereIn("config_id", $taskIds);

        $ret =$where->get();
        $data = self::objToArray($ret);
        return $data;
    }



    public function _getTimeBetweenByCycle($cycle, $time = null)
    {
        $time = $time ?? time();
        # 周期为自然区间
        switch ($cycle) {
            case 0:
                $start_time = 0;
                $stop_time = 0;
                break;

            case 1:
                $start_time = $this->_getTodayStartedAt($time);
                $stop_time = $this->_getTodayStopedAt($time);
                break;

            case 2:
                $start_time = $this->_getWeekStartedAt($time);
                $stop_time = $this->_getWeekStopedAt($time);
                break;

            case 3:
                $start_time = $this->_getMonthStartedAt($time);
                $stop_time = $this->_getMonthStopedAt($time);
                break;

            default:
                $start_time = 0;
                $stop_time = 0;
                break;
        }

        return [$start_time, $stop_time];
    }


    public function _getTodayStartedAt($time){
        return mktime(0,0,0,date('m', $time),date('d', $time),date('Y', $time));
    }

    public function _getTodayStopedAt($time){
        return mktime(0,0,0,date('m', $time),date('d', $time)+1,date('Y', $time))-1;
    }

    public function _getWeekStartedAt($time){
        return mktime(0,0,0,date('m', $time),date('d', $time)-date('w', $time)+1,date('Y', $time));
    }

    public function _getWeekStopedAt($time){
        return mktime(23,59,59,date('m', $time),date('d', $time)-date('w', $time)+7,date('Y', $time));
    }

    public function _getMonthStartedAt($time){
        return mktime(0,0,0,date('m', $time),1,date('Y', $time));
    }

    public function _getMonthStopedAt($time){
        return mktime(23,59,59,date('m', $time),date('t', $time),date('Y', $time));
    }
    /**获取任务完成日志
     * @param $config_id
     * @param $user_id
     * @return mixed
     */
    public function getTaskUserLog($config_id ,$user_id){
        $res = DB::table($this->userTaskLogTable)
            ->select('id')
            ->where("user_id", $user_id)
            ->where("config_id", $config_id)
            ->where(DB::raw("FROM_UNIXTIME(created_at,'%Y-%m-%d')") ,date('Y-m-d'))
            ->where('is_delete' ,0)
            ->first();
        return $this->objToArray($res);
    }

    /**获取奖励内容
     * @param $config_id
     * @return mixed
     */
    public function getRewardRuleByConfigId($config_id){
        $res = DB::table($this->taskRewardRuleTable)
            ->where('config_id' ,$config_id)
            ->first();
        return $this->objToArray($res);
    }
    /**增加总经验值,增加可用经验值/减少可用经验值
     * @param $user_id
     * @param $val
     */
    public function incTaskExperience($user_id ,$val){
        $key = $this->redisTaskUserExperience.date('Ymd');
        $key_avl = $this->redisTaskUserAvlExperience.date('Ymd');
        if($val > 0 ){
//            增加总经验值 + 可用经验值
            Redis::HINCRBY($key ,$user_id ,$val);
            Redis::HINCRBY($key_avl ,$user_id ,$val);
        }else{
//            减少可用经验值
            Redis::HINCRBY($key_avl ,$user_id ,$val);
        }

        if (Redis::TTL($key) == -1) {
            Redis::EXPIRE($key, 2 * 24 * 3600);
        }
        if (Redis::TTL($key_avl) == -1) {
            Redis::EXPIRE($key_avl, 2 * 24 * 3600);
        }
    }

    /**设置任务完成状态
     * @param $config_id
     * @param $user_id
     */
    public function setTaskIsReceive($config_id ,$user_id){
        $key = $this->redisTableUserReceive.date('Ymd');
        Redis::HSET($key ,$user_id.'_'.$config_id ,1);
        if (Redis::TTL($key) == -1) {
            Redis::EXPIRE($key, 2 * 24 * 3600);
        }
    }

    /**获取任务是否完成
     * @param $config_id
     * @param $user_id
     * @return int
     */
    public function getTaskIsReceive($config_id ,$user_id){
        return Redis::HGET($this->redisTableUserReceive.date('Ymd') ,$user_id.'_'.$config_id) ?? 0;
    }

    /**获取当前总经验值
     * @param $user_id
     * @return int
     */
    public function getTaskExperience($user_id){
        return Redis::HGET($this->redisTaskUserExperience.date('Ymd') ,$user_id) ?? 0;
    }

    /**获取可用经验值
     * @param $user_id
     * @return int
     */
    public function getTaskAvlExperience($user_id){
        return Redis::HGET($this->redisTaskUserAvlExperience.date('Ymd') ,$user_id) ?? 0;
    }

    /**领取任务奖励
     * @param $config_id
     * @param $user_id
     * @param $reward_value
     */
    public function receiveTask($config_id ,$user_id ,$reward_value){
        $id = DB::table($this->userTaskRewardLogTable)
            ->insertGetId(array(
                'user_id'=>$user_id ,
                'config_id'=>$config_id ,
                'reward_status' =>1,
                'created_at' =>time() ,
                'reward_value' =>$reward_value
            ));
        if($id){
            $this->setTaskIsReceive($config_id ,$user_id);
            $this->incTaskExperience($user_id ,$reward_value);
        }
    }
}

